
select sl.Branch as slbranch,sl.Type as sltype,sl.Prefix as slprefix,sl.srl as slsrl, sl.DocDate as sldocdate, sl.code as slcode, sl.amt as slamt 
,os.code as oscode, os.Amount  as osamout
,ld.code as ldcode,ld.Debit  as lddebit
,oscodeok = case when sl.code = os.Code then '' else 'N' end
,osamtok = case when sl.amt = os.amount then '' else 'N' end
,oslocationok  = case when sl.LocationCode  = os.LocationCode then '' else 'N' end
,ldcodeok = case when sl.code = ld.Code then '' else 'N' end
,ldamtok = case when sl.amt = ld.Debit  then '' else 'N' end
,ldlocationok  = case when sl.LocationCode  = ld.LocationCode then '' else 'N' end

from 
(select sales.branch,sales.type,sales.prefix,sales.srl,sales.docdate ,sales.code,sales.amt,sales.LocationCode  
 from sales inner join DocTypes  on sales.Branch = DocTypes.branch and sales.type = DocTypes.code 
 where DocTypes.SubType in ('rs','cs','us')
) as sl
left join 
(
	select Outstanding.branch,Outstanding.type,Outstanding.prefix,Outstanding.srl,Outstanding.docdate ,Outstanding.code,Outstanding.Amount ,Outstanding.LocationCode 
	from Outstanding  inner join DocTypes  on Outstanding.Branch = DocTypes.branch and Outstanding.type = DocTypes.code 
	where type =atype and Prefix =aPrefix  and srl = aSerial  and sno  = aSno 
	and DocTypes.SubType in ('rs','cs','us')
) as os on sl.Branch = os.Branch  and sl.Type = os.type and sl.Prefix  = os.Prefix  and sl.Srl = os.Srl 

left join 
(
	select Ledger.branch,Ledger.type,Ledger.prefix,Ledger.srl,Ledger.docdate ,Ledger.code,Ledger.Debit ,Ledger.LocationCode 
	from Ledger  inner join DocTypes  on Ledger.Branch = DocTypes.branch and Ledger.type = DocTypes.code 
	where DocTypes.SubType in ('rs','cs','us') and Ledger.Sno ='00001'
) as ld on sl.Branch = ld.Branch  and sl.Type = ld.type and sl.Prefix  = ld.Prefix  and sl.Srl = ld.Srl 
--where  case when sl.code = os.Code then '' else 'N' end ='n'
--and case when sl.amt = os.amount then '' else 'N' end ='n'
--and case when sl.LocationCode  = os.LocationCode then '' else 'N' end ='n'
--and case when sl.code = ld.Code then '' else 'N' end ='n'
--and case when sl.amt = ld.Debit  then '' else 'N' end='n'
--and case when sl.LocationCode  = ld.LocationCode then '' else 'N' end ='n'